package com.tutos.ui.monitor;

import java.util.Arrays;
import java.util.List;

import javax.inject.Inject;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;

import com.tutos.dao.MateriaDAO;
import com.tutos.dao.MonitorDAO;
import com.tutos.dao.TutoriaDAO;
import com.tutos.model.Materia;
import com.tutos.model.Monitor;
import com.tutos.model.Tutoria;
import com.tutos.ui.TutosApplication;

//import com.tutos.ui.monitor.addTutorial.TutoriaFieldFactory;

import com.vaadin.data.Item;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property;
//import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.BeanItem;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.data.util.IndexedContainer;
import com.vaadin.data.validator.StringLengthValidator;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.ui.AbstractSelect;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.CheckBox;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Field;
import com.vaadin.ui.Form;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.TextField;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.Component;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;

public class Tutorial {
	
	private VerticalLayout layout = new VerticalLayout();
	private Table table = new Table();
	private List<Tutoria> tutorias;
	private Monitor monitor = null;
	private TutoriaDAO tutoriaDao;
	private MonitorDAO monitorDAO;
	private MateriaDAO materiaDAO;
	private ComboBox comboBox;
	final Button editButton = new Button("Editar");
    final Button addButton = new Button();
	
    @Inject
    public Tutorial(TutoriaDAO tutoriaDAO, MonitorDAO monitorDAO, MateriaDAO materiaDAO) {
    	
    	this.tutoriaDao=tutoriaDAO;
    	this.monitorDAO=monitorDAO;
    	this.materiaDAO=materiaDAO;    	    	
    	
    	buildLayout();    
    }	
        
    public void init(){
    	Subject currentUser = SecurityUtils.getSubject();
		monitor=monitorDAO.getMonitorByCorreo((String) currentUser.getSession().getAttribute("username"));
		
		activateControls();
		updateTable();
		
    }
    
    public void init(Monitor monitor){
    	
    	this.monitor = monitor;    	
    	deActivateControls();    	
    	updateTable();
    }
    
    private void activateControls(){
    	editButton.setEnabled(false);
    	editButton.setVisible(false);
    	
    	addButton.setEnabled(true);
    	addButton.setVisible(true);
    }

    private void deActivateControls(){
    	editButton.setEnabled(false);
    	editButton.setVisible(false);
    	
    	addButton.setEnabled(false);
    	addButton.setVisible(false);    	
    }
    
    public void buildLayout(){
    	
        layout.setSpacing(true);
        layout.addComponent(table);
      
        table.setWidth("100%");
        table.setPageLength(15);

        layout.addComponent(editButton);
        layout.setComponentAlignment(editButton, Alignment.BOTTOM_RIGHT);
        layout.addComponent(addButton);
        layout.setComponentAlignment(addButton, Alignment.BOTTOM_RIGHT);


        editButton.addListener(new Button.ClickListener() {        
			
        	private static final long serialVersionUID = 1L;

			@Override
        	public void buttonClick(ClickEvent event) {
                table.setEditable(!table.isEditable());
                editButton.setCaption((table.isEditable() ? "Save" : "Edit"));                                
			}		
        });
        addButton.setDescription("Agregar Tutoria");
        addButton.setIcon(new ThemeResource("add.gif"));  
        addButton.addListener(new ClickListener() {
        	private static final long serialVersionUID = 1L;
        	
        	@Override
        	public void buttonClick(ClickEvent event) {
            
            AddTutorial crearTutoria = new AddTutorial();
            final Window ventanaAddTutorial = new Window("Agregar Tutoria");
             
            ventanaAddTutorial.setSizeUndefined();
            ventanaAddTutorial.addComponent(crearTutoria);
            ventanaAddTutorial.setWidth("420px");
            ventanaAddTutorial.setHeight("-1px");     		
     		ventanaAddTutorial.setModal(true);
      		ventanaAddTutorial.setResizable(false);
          		
      		TutosApplication.getInstance().getMainWindow().addWindow(ventanaAddTutorial);
			ventanaAddTutorial.setVisible(true);
					
            } 			
        });
        
        layout.setComponentAlignment(editButton, Alignment.TOP_RIGHT); 	
    	    	    	    	
    }           
    
    public void updateTable(){
   	 	
		if (monitor != null) {

			tutorias = tutoriaDao.getTutoriasMonitor(monitor);
			IndexedContainer container1 = new IndexedContainer();
			container1.addContainerProperty("costo", Integer.class, "");
			container1.addContainerProperty("informacion", String.class, "");
			container1.addContainerProperty("materia", String.class, "");
			table.setContainerDataSource(container1);

			for (Tutoria tuto : tutorias) {
				Item item = container1.addItem(tuto);
				item.getItemProperty("costo").setValue(tuto.getCosto());
				item.getItemProperty("informacion").setValue(
						tuto.getInformacion());

				Materia materia = materiaDAO.getEntity(tuto.getMateria()
						.getId());

				item.getItemProperty("materia").setValue(materia.getNombre());
			}
		}			
   }
    
	public Component getComponent() {
		return layout;
	}	

	
private class AddTutorial extends VerticalLayout{
		
	private static final long serialVersionUID = 1L;
		
	    Tutoria tutoria;
	    Monitor monitor;
	    TutoriaDAO tutoriaDAO = new TutoriaDAO();
	    MonitorDAO monitorDAO= new MonitorDAO();

	    
	    Button aceptar;
	    final CheckBox addSubject;
	    

	    private static final String COMMON_FIELD_WIDTH = "12em";

	    public AddTutorial() {
	    	
	        tutoria = new Tutoria(); // a person POJO
	        BeanItem<Tutoria> tutoriaItem = new BeanItem<Tutoria>(tutoria); // item from	 
	        final Form tutoriaForm = new FormTutoriaLayout(tutoriaItem);
	        final HorizontalLayout materiaForm = new HorizontalLayout();
	        addSubject = new CheckBox("Agregar Materia");
	        aceptar = new Button("Aceptar");	 
	        
	        
	        aceptar.addListener(new ClickListener() {				
				
	        	private static final long serialVersionUID = 1L;
				@Override
				public void buttonClick(ClickEvent event) {
					Window mainWindow = TutosApplication.getInstance().getMainWindow();
									
						try{
							tutoriaForm.commit();
						}catch(Exception exception){
							mainWindow.showNotification("Datos Invalidos.", Notification.TYPE_ERROR_MESSAGE);
							return;
						}
						
						tutoriaForm.discard();
						Subject currentUser = SecurityUtils.getSubject();						
						monitor =monitorDAO.getMonitorByCorreo((String) currentUser.getSession().getAttribute("username"));																	
						tutoria.setMonitor(monitor);
						tutoriaDAO.insertEntity(tutoria);
						mainWindow.removeWindow(AddTutorial.this.getWindow());
						mainWindow.showNotification("Registro exitoso.", Notification.TYPE_HUMANIZED_MESSAGE);
						updateTable();
					
				}
			});
	        
	        addComponent(tutoriaForm);
	        setComponentAlignment(tutoriaForm, Alignment.MIDDLE_CENTER);
	        
	        addComponent(addSubject);
	        setComponentAlignment(addSubject, Alignment.BOTTOM_CENTER);
	        
	        addSubject.addListener(new Property.ValueChangeListener() {
				private static final long serialVersionUID = 1L;	
				
				public void valueChange(ValueChangeEvent event) {
					boolean value = (Boolean) event.getProperty().getValue();
					
					if(value){
						addMateria crearMateria = new addMateria();			            
			            materiaForm.setSizeUndefined();
			            materiaForm.addComponent(crearMateria);
			            materiaForm.setWidth("420px");
			            materiaForm.setHeight("-1px");	
					}else{
						removeComponent(materiaForm);
						removeComponent(addSubject);
					}
					 

	            }
	        });
	        
	        addSubject.setImmediate(true);	        
            addComponent(materiaForm);
            setComponentAlignment(materiaForm, Alignment.MIDDLE_CENTER);	        	       	        	        	    	  	        	    
	        addComponent(aceptar);	        
	        setComponentAlignment(aceptar, Alignment.BOTTOM_CENTER);	        
	        setWidth("370px");
	        setHeight("-1px");	        	        
	    }

public class FormTutoriaLayout extends Form {

	    	private static final long serialVersionUID = 1L;
	    	
	        private GridLayout ourLayout;

	        public FormTutoriaLayout(BeanItem<Tutoria> tutoriaItem) {
	            setCaption("Datos Tutoria");
	            
	            ourLayout = new GridLayout(2, 4);	           
	            ourLayout.setMargin(true, false, false, true);
	            ourLayout.setSpacing(true);
	            setLayout(ourLayout);
	         
	            setWriteThrough(false); 
	            setInvalidCommitted(false); 

	            setFormFieldFactory(new TutoriaFieldFactory());
	            setItemDataSource(tutoriaItem); 	            
	            setVisibleItemProperties(Arrays.asList(new String[] { "costo",
	                    "informacion", "materia" }));
	        }

	       @Override
	       protected void attachField(Object propertyId, Field field) {
	            if (propertyId.equals("costo")) {
	                ourLayout.addComponent(field, 0, 0);
	            } else if (propertyId.equals("informacion")) {
	                ourLayout.addComponent(field, 1, 0);
	            } else if (propertyId.equals("materia")) {
	                ourLayout.addComponent(field, 0, 1);	           
	        }

	    }
	   }

private class TutoriaFieldFactory extends DefaultFieldFactory {
	    	
	    	private static final long serialVersionUID = 1L;
			
			public TutoriaFieldFactory() {
	        }

	        @Override
	        public Field createField(Item item, Object propertyId,
	                Component uiContext) {
	            Field f = null;

	                f = super.createField(item, propertyId, uiContext);
	            

	            if ("costo".equals(propertyId)) {
	                TextField tf = (TextField) f;
	                tf.setRequired(true);
	                tf.setNullRepresentation("");
	                tf.setRequiredError("Por favor ingrese el costo de la tutoria");
	                tf.setInputPrompt("Costo tutoria");
	                tf.setWidth(COMMON_FIELD_WIDTH);
	               // tf.addValidator(new StringLengthValidator(
	                 //       "El nombre debe tener entre 10 y 30 caracteres", 10, 30, false));
	            } else if ("informacion".equals(propertyId)) {
	                TextField tf = (TextField) f;
	                tf.setRequired(true);
	                tf.setNullRepresentation("");
	                tf.setRequiredError("Por favor ingrese informacion de la tutoria");
	                tf.setInputPrompt("Informacion tutoria");
	                tf.setWidth(COMMON_FIELD_WIDTH);
	                tf.addValidator(new StringLengthValidator(
	           	              "El nombre debe tener entre 50 y 300 caracteres", 5, 300, false));
	            } else if("materia".equals(propertyId)){
	            	comboBox = new ComboBox();	            		            	
	            	comboBox.setCaption("Materia");
	            	comboBox.setPropertyDataSource(item.getItemProperty(propertyId));	            		            		          
	            	comboBox = create(comboBox);	    
	            	return comboBox;
	            }

	            return f;
	        }
	        
	      
	    }

private class addMateria extends VerticalLayout{
	
	private static final long serialVersionUID = 1L;
	 Materia materia;
	 MateriaDAO materiaDAO;
	 Button aceptar;
	 
	 public addMateria() {		
		 materia = new Materia();
		 materiaDAO = new MateriaDAO();
		 BeanItem<Materia> materiaItem = new BeanItem<Materia>(materia); // item from
		 final Form materiaForm = new FormSubjectLayout(materiaItem);
		 aceptar = new Button("Aceptar");
		 
		 addComponent(materiaForm);
		 setComponentAlignment(materiaForm, Alignment.MIDDLE_CENTER);
		 		 
		 addComponent(aceptar);
		 setComponentAlignment(aceptar, Alignment.BOTTOM_CENTER);		 	
	 
	 aceptar.addListener(new ClickListener() {				
			
     	private static final long serialVersionUID = 1L;

			@Override
			public void buttonClick(ClickEvent event) {
				Window mainWindow = TutosApplication.getInstance().getMainWindow();
								
					try{
						materiaForm.commit();
					}catch(Exception exception){
						mainWindow.showNotification("Datos Invalidos.", Notification.TYPE_ERROR_MESSAGE);
						return;
					}
					
					materiaForm.discard();					
					materiaDAO.insertEntity(materia);
					mainWindow.showNotification("Registro exitoso.", Notification.TYPE_HUMANIZED_MESSAGE);
					comboBox=create(comboBox);
				
			}
		});	 
	 
	 }		
}
	  

public class FormSubjectLayout extends Form {

	    	private static final long serialVersionUID = 1L;
	    	
	        private GridLayout ourLayout;

	        public FormSubjectLayout(BeanItem<Materia> materiaItem) {
	            setCaption("Datos Materia");
	           
	            
	            ourLayout = new GridLayout(2, 4);	           
	            ourLayout.setMargin(true, false, false, true);
	            ourLayout.setSpacing(true);
	            setLayout(ourLayout);	         
	            setWriteThrough(false); 
	            setInvalidCommitted(false); 

	            setFormFieldFactory(new MateriaFieldFactory());
	            setItemDataSource(materiaItem); 
	            
	            setVisibleItemProperties(Arrays.asList(new String[] { "nombre",
	                    "descripcion" }));
	        }

	       @Override
	       protected void attachField(Object propertyId, Field field) {
	            if (propertyId.equals("nombre")) {
	                ourLayout.addComponent(field, 0, 0);
	            } else if (propertyId.equals("descripcion")) {
	                ourLayout.addComponent(field, 1, 0);
	            } 	           
	        

	    }
	   }
	    
private class MateriaFieldFactory extends DefaultFieldFactory {
	    	
	    	private static final long serialVersionUID = 1L;
			
			public MateriaFieldFactory() {
	        }

	        @Override
	        public Field createField(Item item, Object propertyId,
	                Component uiContext) {
	            	Field f = null;
	                f = super.createField(item, propertyId, uiContext);
	            
	            if ("nombre".equals(propertyId)) {
	                TextField tf = (TextField) f;
	                tf.setRequired(true);
	                tf.setNullRepresentation("");
	                tf.setRequiredError("Por favor ingrese el nombre de la materia");
	                tf.setInputPrompt("Costo tutoria");
	                tf.setWidth(COMMON_FIELD_WIDTH);
	               // tf.addValidator(new StringLengthValidator(
	                 //       "El nombre debe tener entre 10 y 30 caracteres", 10, 30, false));
	            } else if ("descripcion".equals(propertyId)) {
	                TextField tf = (TextField) f;
	                tf.setRequired(true);
	                tf.setNullRepresentation("");
	                tf.setRequiredError("Por favor ingrese la descripcion de la materia");
	                tf.setInputPrompt("Informacion tutoria");
	                tf.setWidth(COMMON_FIELD_WIDTH);
	                tf.addValidator(new StringLengthValidator(
	           	              "El nombre debe tener entre 50 y 300 caracteres", 5, 300, false));
	            } 

	            return f;
	        }
	        
	      
	    }	    
	}
	public ComboBox create(ComboBox combo){
		
		BeanItemContainer<Materia> container = new BeanItemContainer<Materia>(Materia.class);
    	MateriaDAO mat = new MateriaDAO();
    	List<Materia> materias=mat.getAll();	            		            		         	            
    	for(Materia mater : materias){	            	
    		container.addBean(mater);	            	
    	}	  
    	
    	
    	combo.setImmediate(true);
    	combo.setContainerDataSource(container);
    	combo.setItemCaptionMode(AbstractSelect.ITEM_CAPTION_MODE_PROPERTY);
    	combo.setItemCaptionPropertyId("nombre");
    	
    	
    	return combo;
	}
}
